import * as THREE from '../../build/three.module.js';
import { OrbitControls } from '../../jsm/controls/OrbitControls.js';
import { ConvexBufferGeometry } from '../../jsm/geometries/ConvexGeometry.js';

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000);

// 环境光
scene.add(new THREE.AmbientLight(0x222222));

// 点光源
const light = new THREE.PointLight(0xffffff, 1);

// 辅助线
scene.add(new THREE.AxesHelper(20));

// 贴图
const loader = new THREE.TextureLoader();
const txr = loader.load('../../textures/sprite/disc.png');

// 几何体组
const group = new THREE.Group();
scene.add(group);

// 结合体顶点
const vertices = new THREE.DodecahedronGeometry(10).vertices;

// 可选效果-顶点摇摆
// const baseRandom = 3;
// for(let i = 0; i < vertices.length; i += 1) {
//   vertices[i].add(new THREE.Vector3(Math.random() * baseRandom, Math.random() * baseRandom,Math.random() * baseRandom).multiplyScalar(2))
// }

// 材质-点
const pointMtl = new THREE.PointsMaterial({
  color: 0x0000ff,
  map: txr,
  size: 1,
  alphaTest: .5
});

// 几何体-点
const pointStl = new THREE.BufferGeometry().setFromPoints(vertices);

// 网格模型-点
const pointsMesh = new THREE.Points(pointStl, pointMtl);
group.add(pointsMesh);

// 材质-面
const hullMtl = new THREE.MeshLambertMaterial({
  color: 0xffffff,
  opacity: .5,
  transparent: true
});

// 几何体面
const hullStl = new ConvexBufferGeometry(vertices);

// 网格模型-面
let mesh = new THREE.Mesh(hullStl, hullMtl);
mesh.material.side = THREE.BackSide
mesh.renderOrder = 0;
group.add(mesh);

mesh = new THREE.Mesh(hullStl, hullMtl.clone());
mesh.material.side = THREE.FrontSide
mesh.renderOrder = 1;
group.add(mesh);

// 相机
const k = innerWidth / innerHeight,
      s = 40,
      camera = new THREE.PerspectiveCamera(s, k, 1, 100);
camera.position.set(15, 20, 30);
camera.lookAt(scene.position);
camera.add(light); // 将光源与相机绑定
scene.add(camera);

// 渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

// 控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.minDistance = 20;
controls.maxDistance = 50;
controls.maxPolarAngle = Math.PI / 2;

// 监听窗口尺寸变化
const handleWindowResize = () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);
}
window.addEventListener('resize', handleWindowResize);

// 渲染函数
const render = () => {
  renderer.render(scene, camera);
}

// 动画
const animate = () => {
  requestAnimationFrame(animate);
  group.rotation.y += .005;
  render();
}
animate();